//1.基本结构 2.then方法  3.all方法  4.reace方法  5.resolve方法  6.reject方法  7.finally方法
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"

class Promise {
  PromiseState = PENDING
  PromiseResult = undefined

  fulfilledCbs = []
  rejectedCbs = []
  constructor(excutor) {
    try {
      excutor(this.resolve.bind(this), this.reject.bind(this))
    } catch (err) {
      this.reject(err)
    }
  }
  resolve(val) {
    if (this.PromiseState !== PENDING) return
    this.PromiseState = FULFILLED
    this.PromiseResult = val
  }
  reject(reason) {
    if (this.PromiseState !== PENDING) return
    this.PromiseState = REJECTED
    this.PromiseResult = reason
  }
  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (val) => val
    onRejected =
      typeof onRejected === "function"
        ? onFulfilled
        : (reason) => {
            throw reason
          }

    if (this.PromiseState === FULFILLED) {
    } else if (this.PromiseState === REJECTED) {
    } else if (this.PromiseState === PENDING) {
      this.fulfilledCbs.push(onFulfilled.bind(this, this.PromiseResult))
      this.rejectedCbs.push(onRejected.bind(this, this.PromiseResult))
    }
  }
}
